/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package horsechess.server.data;

import horsechess.server.gui.GUIServer;
import horsechess.util.Status;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

/**
 *
 * @author Nguyen Hoang Thinh
 * Email : hoangthinh1989@gmail.com
 */
public class ServerHandler implements Runnable {

    public int port = 7777;
    public String serverAddr = "225.4.5.6";
    public static Vector<RoomManager> listOfRoom;
    public static Status status;
    private String receiveMessage;
    private static boolean roomFull = false;
    private GUIServer guiServer;

    public ServerHandler(GUIServer uiServer) {
        listOfRoom = new Vector<RoomManager>(2);
        //this.guiServer=gui;
        listOfRoom.add(new RoomManager("Server A",uiServer));
        listOfRoom.add(new RoomManager("Server B",uiServer));
        this.guiServer=uiServer;
    }

    

    public static boolean isRoomFull() {
        if (listOfRoom.get(0).isFull() && listOfRoom.get(1).isFull()) {
            roomFull = true;
        }
        return roomFull;
    }

    /**
     *
     */
    public void recivingClient() {
        try {
            GUIServer.txtServerStatus.setText("Server is waiting for client connection at port: " + port);
            ServerSocket serverSocket = new ServerSocket(port);
            while (!isRoomFull()) {

                Socket clientSocket = serverSocket.accept();
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
                // Mac dinh la` vo room 1
                ClientHandler client = new ClientHandler(clientSocket, guiServer);
                Thread t = new Thread(client);
                t.start();
                if (!listOfRoom.get(0).isFull()) {
                    listOfRoom.get(0).registerClient(client);
                    client.setRoom(listOfRoom.get(0));
                    listOfRoom.get(0).advertiseRoom();
                } //if room 1 fulls. Other players will adds to room 2
                else {
                    listOfRoom.get(1).registerClient(client);
                    client.setRoom(listOfRoom.get(1));
                    listOfRoom.get(1).advertiseRoom();
                }

                isRoomFull();
                status = Status.WAITING;
                client.send(Status.toString(Status.CONNECTING));
                //System.out.println("Sending status connecting");
                GUIServer.txtServerStatus.setText("One client has been connected successful to the server !!!");

            }
        } catch (Exception e) {
            status = Status.EXCEPTION;
            GUIServer.txtServerStatus.setText("Server got error: " + e.getMessage());
        }
    }

    public void run() {
        recivingClient();
    }
}
